//获取应用实例
const app = getApp();
var getModel = false;
var util = require('../../utils/util.js');
var _this, monthsDays = [],
  times = ['00:00 - 03:00', '03:00 - 06:00', '06:00 - 09:00', '09:00 - 12:00', '12:00 - 15:00', '15:00 - 18:00', '18:00 - 21:00', '21:00 - 00:00'];
var timeSecond = util.formatTime(new Date());
var date = timeSecond.split(" ")[0],
  year = parseInt(date.split("-")[0]),
  month = parseInt(date.split("-")[1]),
  day = parseInt(date.split("-")[2]),
  nowTime = 3, leapYear = false,
  timeNew = timeSecond.split(" ")[1];
// 计算是否是闰年
if (year % 400 == 0) {
  leapYear = true;
} else if (year % 4 == 0 && year % 100 != 0) {
  leapYear = true;
}
// 循环月份和日期
for (var a = month; a < 13; a++) {
  var today = 1, oneMonth = 31
  // 判断当前日期之后
  if (a == month) {
    today = day;
  }
  // 判断大小月
  if (a == 2) {
    // 判断是否是闰年
    if (leapYear && a == 2) {
      oneMonth = 29;
    } else {
      oneMonth = 28;
    }
  } else if (a == 1 || a == 3 || a == 5 || a == 7 || a == 8 || a == 10 || a == 12) {
    oneMonth = 31;
  } else if (a == 4 || a == 6 || a == 9 || a == 11) {
    oneMonth = 30;
  }
  for (var b = today; b < oneMonth + 1; b++) {
    var today = a + '月 ' + b + '日';
    monthsDays.push(today);
  }
}
// 获取当前时间
timeNew = parseInt(timeNew.split(":")[0])
//timeNew = 22
if (timeNew < 3) {
  nowTime = 1;
} else if (timeNew < 6) {
  nowTime = 2;
} else if (timeNew < 9) {
  nowTime = 3;
} else if (timeNew < 12) {
  nowTime = 4;
} else if (timeNew < 15) {
  nowTime = 5;
} else if (timeNew < 18) {
  nowTime = 6;
} else if (timeNew < 21) {
  nowTime = 7;
} else {
  nowTime = 8;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    Maintenance: app.globalData.Maintenance,
    recommendProductsList:[],
    productFee: 0,// 总价
    brandLogo: null,
    brandModelName: '',
    buttonClicked: false,
    delBtnWidth: 150,//删除按钮宽度单位（rpx）
    // 日期 时间
    monthsDays: [],
    times: times,
    monthsDay: '请选择保养时间',
    time: '',
    dateAndAddress:true,
    detailFee:false,
    newMtServer:true,  // 防重复提交
    chooseDateAddress: true,
    scrollSwitch:true,
    startRecord:'start',
    closeOtherItem:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this
    if (options){
      getModel = options.getModel;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    _this.init();
  },
  init:function(){
    // 维修
    let serviceType = [
      {
        image: 'icon_46_engine_',
        choose: true,
        name: '发动机',
        id: 0
      }, {
        image: 'icon_47_pressure_',
        choose: false,
        name: '液压件',
        id: 0
      }, {
        image: 'icon_48_device_',
        choose: false,
        name: '电器件',
        id: 0
      }, {
        image: 'icon_49_Chassis_',
        choose: false,
        name: '底盘件',
        id: 0
      }, {
        image: 'icon_50_get_',
        choose: false,
        name: '结构件',
        id: 0
      }, {
        image: 'icon_51_other_',
        choose: false,
        name: '其他',
        id: 0
      },
    ]
    let ReplacementType = [{
        image: 'icon_hj-1-',
        choose: true,
        name: '换支重轮',
        id: 5
      },{
        image: 'icon_hj-2-',
        choose: false,
        name: '换拖链轮',
        id: 3
      },{
        image: 'icon_hj-3-',
        choose: false,
        name: '换引导轮',
        id: 3
      },{
        image: 'icon_hj-4-',
        choose: false,
        name: '换履带板',
        id: 3
      }, {
        image: 'icon_hj-5-',
        choose: false,
        name: '换油封',
        id: 3
      }]
    _this.setData({
      saveMapArea: app.globalData.Maintenance.userArea,
      brandLogo: app.globalData.xieYouUserInfoRoot.userBrandModel.brand.brandLogo,
      brandModel: app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel,
      serviceType: app.globalData.Maintenance.serviceType,
      serviceTypeNav: app.globalData.Maintenance.serviceType == '0' ? serviceType : ReplacementType,
      //categoryNameId: app.globalData.Maintenance.serviceType == '0' ? 7 : 5,
    })
    if(_this.data.serviceType == '3'){
      let Maintenance = _this.data.Maintenance;
        Maintenance.serviceType = '5';
        _this.setData({
          Maintenance: Maintenance,
          serviceType: '5'
        })
    }
    _this.initEleWidth();
    _this.getItem();
    // 维修时间插件
    _this.firstDate();
    // 获取推荐配件
    // if (app.globalData.Maintenance.recommendProductsList && getModel) {
    //   _this.setData({
    //     recommendProductsList: app.globalData.Maintenance.recommendProductsList
    //   })
    //   _this.totalPrice();// 计算总价
    //   // 取消加载中
    //   wx.hideLoading();
    // } else {
    // }
  },
  getItem:function(){
    // wx.showLoading({
    //   title: '加载中',
    // })
    wx.setNavigationBarTitle({
      title: app.globalData.Maintenance.serviceTitle
    })
    if(_this.data.Maintenance.serviceType != 0){
      _this.getRecommendedProductsList()
    }
  },
  /*  删除产品 */
  dataChangeDelete: function (e) {
    // 获取参数 —— outerIndex index
    var outerIndex = e.target.dataset.outerIndex ? e.target.dataset.outerIndex : e.currentTarget.dataset.outerIndex;
    var index = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
    var productsList = _this.data.recommendProductsList
    productsList[outerIndex].recommendProductList.splice(index, 1);
    if (productsList[outerIndex].recommendProductList.length == 0){
      productsList[outerIndex].checked = false;
    }
    _this.setData({
      recommendProductsList: productsList
    })
    app.globalData.Maintenance.recommendProductsList = productsList;
    _this.totalPrice();
  },
  /*  加减数量 */
  dataChangeLess:function(e){
    // 获取参数 —— outerIndex index
    var outerIndex = e.target.dataset.outerIndex ? e.target.dataset.outerIndex : e.currentTarget.dataset.outerIndex;
    var index = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
    var productsList = _this.data.recommendProductsList;
    if (productsList[outerIndex].recommendProductList[index].countShopCar > 1){
      productsList[outerIndex].recommendProductList[index].countShopCar = productsList[outerIndex].recommendProductList[index].countShopCar - 1;
    }else{
      util.alertMsg('提示','是否要删除该产品',function(){
        _this.dataChangeDelete(e);
      },function(){})
    }
    _this.setData({
      recommendProductsList: productsList
    })
    _this.totalPrice();
  },
  dataChangeAdd:function(e) {
    // 获取参数 —— outerIndex index
    var outerIndex = e.target.dataset.outerIndex ? e.target.dataset.outerIndex : e.currentTarget.dataset.outerIndex;
    var index = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
    var productsList = _this.data.recommendProductsList
    productsList[outerIndex].recommendProductList[index].countShopCar = productsList[outerIndex].recommendProductList[index].countShopCar + 1;
    _this.setData({
      recommendProductsList: productsList
    })
    _this.totalPrice();
  },
  // 选择产品
  commodityOperate: function (e) {
    // 获取参数 —— outerIndex index
    var outerIndex = e.target.dataset.outerIndex ? e.target.dataset.outerIndex : e.currentTarget.dataset.outerIndex;
    var index = e.target.dataset.index ? e.target.dataset.index : e.currentTarget.dataset.index;
    var productsList = _this.data.recommendProductsList;
    var originalRecommend = _this.data.originalRecommend;
    productsList[outerIndex].checked = !!productsList[outerIndex].checked ? !productsList[outerIndex].checked : true;
    if (productsList[outerIndex].checked){
      productsList[outerIndex].recommendProductList = originalRecommend[outerIndex].recommendProductList
    }
    _this.setData({
      recommendProductsList: productsList
    })
    _this.totalPrice();
  },
  /* 总价 */
  totalPrice:function(){
    var productFee = 0, serviceFee = 0, shopCar = [];
    var productsList = _this.data.recommendProductsList,
      Maintenance = _this.data.Maintenance;
    for (var i = 0; i < productsList.length; i++) {
      var b = productsList[i].recommendProductList;
      // if (b && productsList[i].checked){
      //   for (var a = 0; a < b.length; a++) {
      //     var countShopCar = b[a].countShopCar;
      //     var price = b[a].price / 100;
      //     productFee += countShopCar * price;
      //   }
      // }
      if (productsList[i].checked) {
        var b = productsList[i].recommendProductList;
        for(var a = 0; a<b.length;a++){
          var shopCarData = {
            brandId: null,
            brandName: null,
            categoryCode: b[a].categoryId,
            categoryName: productsList[i].serviceItem,
            count: b[a].countShopCar,
            imgPath: b[a].cover,
            modelName: null,
            price: b[a].price,
            productId: b[a].id,
            productName: b[a].name,
            seckill: b[a].seckill,
            programId: productsList[i].id
          };
          shopCar.push(shopCarData);
        }
      }
    }
    // if (Maintenance.serviceType == '2'){
    //   productFee >= 500 ? serviceFee = 0 : serviceFee=100;
    // } else if (Maintenance.serviceType == '1'){
    //   productFee >= 1000 ? serviceFee = 0 : serviceFee = 200;
    // }
    // 去核算接口
    _this.setData({
      // productFee: productFee,
      // serviceFee: serviceFee,
      shopCar: shopCar
    })
    _this.priceDetail();
    console.log('$scope.payload.productFee111111111111=', productFee);
  },
  // 切换机型
  userModel() {
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        title: "goback",
        url: '/pages/index/user-model/user-model?goBack=recommend'
      })
    }
  },
  newProductsList(e){
    // 获取参数 —— outerIndex index
    var outerIndex = e.target.dataset.outerIndex || e.target.dataset.outerIndex == 0  ? e.target.dataset.outerIndex : '';
    var index = e.target.dataset.index || e.target.dataset.index == 0 ? e.target.dataset.index : '';
    var categoryId = e.target.dataset.categoryId ? e.target.dataset.categoryId : '';
    var parentCategoryId = e.target.dataset.parentCategoryId ? e.target.dataset.parentCategoryId : '';
    var urlChangeProduct = 'change-product/change-product';
    //采集商UserCode 添加替换产品 筛选
    //_this.selectProduct(categoryId, outerIndex, index);
    // // 改变弹窗状态
    // _this.setData({
    //   selectProductFilterBox : true
    // })
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        title: "goback",
        url: '/pages/recommend-products-list/change-product/change-product?categoryId=' + categoryId + '&outerIndex=' + outerIndex + '&index=' + index + '&parentCategoryId=' + parentCategoryId
      })
    }
  },
  /*  修改地址 */
  changeAddress:function(){
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/little-service-massage/little-service-massage'
      })
    }
  },
  getRecommendedProductsList:function(){
    let data = _this.data.Maintenance, shopCar = [];//, categoryNameId=null;
    data.brandModelId = app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel.id
    // if (data.serviceType == '3'){
    //   categoryNameId = _this.data.categoryNameId
    // }
    app.getRecommendedProductsList(data, function (res) {
      console.log('保养推荐商品：', res);
      var dataBox = res;
      for (var i = 0; i < dataBox.length; i++) {
        var b = dataBox[i].recommendProductList;
        if (b){
          for (var a = 0; a < b.length; a++) {
            b[a].countShopCar = 1
          }
        }
      }
      app.globalData.Maintenance.recommendProductsList = dataBox;
      _this.setData({
        recommendProductsList: dataBox,
        originalRecommend: dataBox,
        // shopCar: shopCar
      })
      _this.totalPrice();// 计算总价
      // 取消加载中
      wx.hideLoading();
    });//, categoryNameId);
  },
  /**
   * 2018-9-18
   */
  /**
   * 滑动删除
   */ 
  touchS: function (e) {
    var outerIndex = e.currentTarget.dataset.outerIndex, 
      index = e.currentTarget.dataset.index,
      recommendProductsList = _this.data.recommendProductsList;
    for (var i = 0; i < recommendProductsList.length; i++) {
      if (recommendProductsList[i].recommendProductList){
        for (var a = 0; a < recommendProductsList[i].recommendProductList.length; a++) {
          recommendProductsList[i].recommendProductList[a].txtStyle = 'left:0px;';
        }
      }
    }
    _this.setData({
      recommendProductsList: recommendProductsList
    })
    if (e.touches.length == 1) {
      _this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    var test = true;
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = _this.data.startX - moveX;
      var delBtnWidth = _this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        test = false;
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var outerIndex = e.currentTarget.dataset.outerIndex,
        index = e.currentTarget.dataset.index,
        recommendProductsList = _this.data.recommendProductsList;
      recommendProductsList[outerIndex].recommendProductList[index].txtStyle = txtStyle;
      _this.setData({
        recommendProductsList: recommendProductsList,
        scrollSwitch: test
      })
    }
  },
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = _this.data.startX - endX;
      var delBtnWidth = _this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var outerIndex = e.currentTarget.dataset.outerIndex,
        index = e.currentTarget.dataset.index,
        recommendProductsList = _this.data.recommendProductsList;
      recommendProductsList[outerIndex].recommendProductList[index].txtStyle = txtStyle;
      _this.setData({
        recommendProductsList: recommendProductsList
      })
      setTimeout(function(){
        _this.setData({
          scrollSwitch: true,
        })
      },200)
    }
  },
  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);//以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(_this.data.delBtnWidth);
    _this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  // 地址
  // 初始化时间选择
  firstDate: function () {
    var _this = this;
    var val = [0, nowTime], monthsDaysVal = 0;
    // 判断 nowTime=8
    if (nowTime == 8) {
      val = [1, nowTime - 1];
      monthsDaysVal = 1;
    }
    _this.setData({
      monthsDays: monthsDays,
      times: times,
      //monthsDay: month + '月 ' + day + '日',
      //time: times[nowTime],
      value: val,
      year: year,
      nowTime: nowTime,
      monthsDaysVal: monthsDaysVal
    })
  },
  // 修改日期
  bindDateChange: function (e) {
    var val = e.detail.value;
    var _this = this;
    _this.setData({
      monthsDaysVal: val[0]
    })
    var monthsDaysVal = _this.data.monthsDaysVal,
      time = times[val[1]],
      monthsDay = monthsDays[monthsDaysVal];
    // 判断今天是否能选
    if (monthsDaysVal == 0 && nowTime == 8) {
      monthsDay = monthsDays[1];
      _this.setData({
        monthsDay: monthsDays[1],
        value: [1, val[1]],
        monthsDaysVal: 1
      })
    }
    // 判断时间段是否能选
    else if (monthsDaysVal == 0 && val[1] < nowTime) {
      var chooseTime = nowTime;
      if (nowTime == 8) {
        chooseTime = chooseTime - 1
      }
      time = times[chooseTime];
      _this.setData({
        monthsDay: monthsDay,
        time: times[chooseTime],
        value: [0, chooseTime]
      })
    } else {
      _this.setData({
        monthsDay: monthsDay,
        time: time,
        value: [val[0], val[1]]
      })
    }
    // // 拼凑 时间段
    // var timePs = monthsDay.split("月")
    // var monthNew = timePs[0];
    // var dayNew = timePs[1].split("日")[0];
    // app.globalData.Maintenance.serviceDate = year + '-' + monthNew + '-' + dayNew + ' 00:00';
  },
  // 打开关闭时间选择
  openCloseDateChoose: function () {
    var _this = this;
    var chooseDate = !_this.data.chooseDate,
      val = _this.data.value,
      valTime = val[1];
    if (valTime == 8) {
      valTime = valTime - 1
    }
    var monthsDay = monthsDays[val[0]],
      time = times[val[1]];
    var val = _this.data.value;
    _this.setData({
      chooseDate: chooseDate,
      monthsDay: monthsDay,
      time: time,
      value: val
    })
    if (!chooseDate) {
      var monthChoose = monthsDay.split("月")[0],
        dayChoose = monthsDay.split(" ")[1];
      dayChoose = dayChoose.split("日")[0]
      // 年月日
      var serviceDate, serviceTimeBegin, serviceTimeEnd;
      serviceDate = year + '-' + monthChoose + '-' + dayChoose + ' 00:00';
      // 开始结束时间
      serviceTimeBegin = time.split(' - ')[0] + ':00'
      serviceTimeEnd = time.split(' - ')[1] + ':00'
      _this.setData({
        serviceDate: serviceDate,
        serviceTimeBegin: serviceTimeBegin,
        serviceTimeEnd: serviceTimeEnd
      })
    }


  },
  // 明细
  detailFeeFun:function(e){
    var detailFee = _this.data.detailFee;
    _this.setData({
      detailFee: !detailFee
    })
  },
  // 提交订单
  // 验证信息
  verifyService: function () {
    var _this = this;
    wx.showLoading({
      title: '加载中',
    })
    var shopCar = [];
    var dataBox = _this.data.recommendProductsList;
    for (var i = 0; i < dataBox.length; i++) {
      var b = dataBox[i].recommendProductList;
      if (b && dataBox[i].checked){
        for (var a = 0; a < b.length; a++) {
          var shopCarData = {
            brandId: null,
            brandName: null,
            categoryCode: b[a].categoryId,
            categoryName: dataBox[i].name,
            count: b[a].countShopCar,
            imgPath: b[a].cover,
            modelName: null,
            price: b[a].price,
            productId: b[a].id,
            productName: b[a].name,
            seckill: b[a].seckill
          };
          shopCar.push(shopCarData);
        }
      }
    }
    app.globalData.Maintenance.shopCar = shopCar;
    // 2018-5-21 修改小保养
    if (_this.data.time == null || _this.data.time==''){
      wx.hideLoading();
      util.alertMsg('警告', '请选择您的服务时间', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    // Map选择的的地址
    var saveMapArea = _this.data.saveMapArea;
    if (saveMapArea.formattedAddresses == null || saveMapArea.formattedAddresses == ''){
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请选择您的保养地址', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    if (_this.data.brandModel.id == null) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请选择你的机型', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    if (_this.data.Maintenance.serviceType == '' || _this.data.Maintenance.serviceType == null) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请选择你的维修类型', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    // app数据更新 时间 姓名 电话 详细地址
    _this.applyServiceWx();
  },
  applyServiceWx: function () {
    var _this = this;
    var data = {
      latitude: _this.data.saveMapArea.latitude,// 经度
      longitude: _this.data.saveMapArea.longitude, //维度
      country: _this.data.saveMapArea.country,//国家
      province: _this.data.saveMapArea.province,  //省
      city: _this.data.saveMapArea.city,//城市
      area: _this.data.saveMapArea.district, //district 地区
      areaCode: _this.data.saveMapArea.adcode, // 地区areaCode
      detailAddress: _this.data.saveMapArea.formattedAddresses, //详细地址

      userCode: app.globalData.xieYouUserInfo.code,//  userCode
      contact: app.globalData.xieYouUserInfo.nickname,  //contact联系人
      contactPhone: app.globalData.xieYouUserInfo.phone, //contactPhone 联系电话
      //repairmanCode: payload.repairmanCode,//维修工编码 支付后在匹配维修师

      serviceType: _this.data.Maintenance.serviceType, //服务类型
      //categoryNameId: categoryNameId,// 故障类型
      //description: payload.description, //description 描述
      serviceDate: _this.data.serviceDate,//serviceDate 服务日期
      brandId: app.globalData.xieYouUserInfoRoot.userBrandModel.brand.id,
      brandModelId: app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel.id,
      brandModelName: app.globalData.xieYouUserInfoRoot.userBrandModel.brand.name + '/' +app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel.name,
      shopCar: _this.data.shopCar
    };
    if (_this.data.Maintenance.serviceType == '1' || _this.data.Maintenance.serviceType == '2') {
      data.servicePlaceType = 0;
      data.serviceTimeBegin = _this.data.serviceTimeBegin;// 保养开始时间
      data.serviceTimeEnd = _this.data.serviceTimeEnd;      // 保养结束时间
    }
    if (_this.data.newMtServer) {
      _this.setData({
        newMtServer: false// 防止重复提交
      });
      app.applyService(data, function (rs) {
        if (rs) {
          if (rs.status == 'success') {
            // 取消加载中
            wx.hideLoading();
            wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 1500,
              mask: true,
              success: function () {
                // // 核算订单
                // 更新首页订单
                app.refreshIndex();
                //跳转 mtOrderTabPage
                // 保养订单 
                if (!_this.data.buttonClicked) {
                  util.buttonClicked(_this);
                  wx.navigateTo({
                    url: '/pages/service-detail/service-detail?id=' + rs.data.id + '&type=ing' + '&tab=1'
                  })
                }
              }
            })
            // $state.go('mt.userOrderDetail', { id: rs.data.id }, true);
          } else {
            // 取消加载中
            wx.hideLoading();
            util.alertMsg('错误', rs.message, function () {
              console.log('用户点击确定')
            }, function () {
              console.log('用户点击取消')
            });
          }
        } else {
          util.alertMsg('错误', '网络异常, 请稍后再试', function () {
            console.log('用户点击确定')
          }, function () {
            console.log('用户点击取消')
          });
        }
      });

    } else {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('提示', '请勿重复提交订单', function () {
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }
      }, function () {
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }
      });
    }
  },
  priceDetail:function(){
    var _this = this;
    var data = {
      latitude: _this.data.saveMapArea.latitude,// 经度
      longitude: _this.data.saveMapArea.longitude, //维度
      country: _this.data.saveMapArea.country,//国家
      province: _this.data.saveMapArea.province,  //省
      city: _this.data.saveMapArea.city,//城市
      area: _this.data.saveMapArea.district, //district 地区
      areaCode: _this.data.saveMapArea.adcode, // 地区areaCode
      detailAddress: _this.data.saveMapArea.formattedAddresses, //详细地址

      userCode: app.globalData.xieYouUserInfo.code,//  userCode
      contact: app.globalData.xieYouUserInfo.nickname,  //contact联系人
      contactPhone: app.globalData.xieYouUserInfo.phone, //contactPhone 联系电话
      //repairmanCode: payload.repairmanCode,//维修工编码 支付后在匹配维修师

      serviceType: _this.data.Maintenance.serviceType, //服务类型
      //categoryNameId: categoryNameId,// 故障类型
      //description: payload.description, //description 描述
      serviceDate: _this.data.serviceDate,//serviceDate 服务日期
      brandId: app.globalData.xieYouUserInfoRoot.userBrandModel.brand.id,
      brandModelId: app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel.id,
      shopCar: _this.data.shopCar
    };
    if (_this.data.Maintenance.serviceType == '1' || _this.data.Maintenance.serviceType == '2') {
      data.servicePlaceType = 0;
      data.serviceTimeBegin = _this.data.serviceTimeBegin;// 保养开始时间
      data.serviceTimeEnd = _this.data.serviceTimeEnd;      // 保养结束时间
    }
    app.priceDetail(data, function (rs) {
      if (rs.data) {
        var data = rs.data.data;
        console.log(data)
        _this.setData({
          totalFee: data.totalFeeDiscounted,
          productFee: data.productFee,
          serviceFee: data.serviceFee,
          trafficFee: data.trafficFee,
          serviceFeeOriginal: data.serviceFeeOriginal,
          freeServiceProductFee: data.freeServiceProductFee,
          productFeeOriginal: data.productFeeOriginal
          // shopCar: shopCar
        })
        console.log(rs);
      } 
    });
  },
  goToH5:function(){
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/protocol/index?name=xieyou-repairman-settlement'
      });
    }
  },
  chooseDateAddressFun:function(){
    var chooseDateAddress = _this.data.chooseDateAddress;
    _this.setData({
      chooseDateAddress: !chooseDateAddress
    })
  },
  feeMassage:function(e){
    var fee = e.target.dataset.type;
    if (fee == 'serviceFee'){
      _this.setData({
        serviceFeeMag:true
      })
      setTimeout(function(){
        _this.setData({
          serviceFeeMag: false
        })
      },5000)
    }else{
      _this.setData({
        trafficFeeMag: true
      })
      setTimeout(function () {
        _this.setData({
          trafficFeeMag: false
        })
      }, 5000)
    }
  },
  startRecord:function(e){
    let status = e.currentTarget.dataset.status;
    if (status == 'start'){
      _this.setData({ startRecord: 'end' })
      wx.startRecord({
        success(res) {
          let tempFilePath = res.tempFilePath
          let data = {};
          //
          data.engine_type = 'sms16k';
          data.aue = 'raw';
          data.audio = util.base64_encode(encodeURIComponent(tempFilePath));
          wx.request({
            url: 'http://api.xfyun.cn/v1/service/v1/iat',
            method: 'POST',
            data: data,
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            success: function (res) {
              console.log(res);
            },
            fail: function (res) {
              console.log('获取用户信息5=', res);
              console.log(res);
            },
            complete:function(res){
              console.log(res)
            }
          })
        },
        fail(res){
          console.log('res1=', res);
        },
        complete(res) {
          console.log('res2=', res);
        }
      })
    }else{
      _this.setData({ startRecord: 'start' })
      wx.stopRecord() // 结束录音
    }
  },
  // 开关
  toggleSwitch:function(e){
    let name = e.currentTarget.dataset.name;
    let value = !_this.data[name]
    _this.setData({
      [name]: value
    })
  },
  // 维修 换件 选择类型
  chooseMaintainType(e) {
    var index = e.currentTarget.dataset.index,
      data = _this.data.Maintenance,
      maintainType = _this.data.serviceTypeNav;
    for (var i = 0; i < maintainType.length; i++) {
      maintainType[i].choose = false;
    }
    maintainType[index].choose = true;
    data.serviceType = maintainType[index].id
    _this.setData({
      serviceTypeNav: maintainType,
      Maintenance: data,
      serviceType: maintainType[index].id
    })
    if(_this.data.Maintenance.serviceType >= 3){
      _this.getRecommendedProductsList()
    }
  },
})

